package org.pearl.account.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.pearl.account.dao.AccountTblMapper;
import org.pearl.account.entity.AccountTbl;
import org.pearl.account.feign.OrderClint;
import org.pearl.account.feign.StorageApi;
import org.pearl.account.service.AccountTblService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author td
 * @since 2020-01-02
 */
@Service
@Slf4j
public class AccountTblServiceImpl extends ServiceImpl<AccountTblMapper, AccountTbl> implements AccountTblService {


    @Autowired
    AccountTblMapper accountTblMapper;
    @Autowired
    OrderClint orderClint;
    @Autowired
    StorageApi storageApi;

    @Override
    public Object prepareBuy(String userId, String code, Long count) {
        log.info("开始TCC xid:" + RootContext.getXID());
        //1.查询账户 扣款
        AccountTbl accountTbl = accountTblMapper.selectById(userId);
        AccountTbl accountTbl1 = accountTbl.setMoney(accountTbl.getMoney() - count);
        accountTblMapper.updateById(accountTbl1);
        //2.远程创建订单
        orderClint.insertOrder(accountTbl.getUserId(), code, count);
        //3.远程扣库存
        storageApi.tcc("iphone11", count);
        return "执行完毕！";
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        log.info("xid = " + actionContext.getXid() + "提交成功");
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        // 获取下单时的提交参数
        String userId = actionContext.getActionContext("userId").toString();
        Long count = Long.parseLong(actionContext.getActionContext("count").toString());
        // 进行分支事务扣掉的金额回滚
        AccountTbl accountTbl = accountTblMapper.selectById(userId);
        AccountTbl accountTbl1 = accountTbl.setMoney(accountTbl.getMoney() + count);
        accountTblMapper.updateById(accountTbl1);
        log.info("xid = " + actionContext.getXid() + "进行回滚操作");
        return true;
    }
}
